<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Wilead\ApiBundle\Controller;

use Doctrine\DBAL\Query\QueryBuilder;
use Wilead\IArtistBundle\Entity\User AS User;
use Wilead\IArtistBundle\Form\UserType;
use FOS\RestBundle\View\View AS FOSView;
use FOS\RestBundle\View\RouteRedirectView;
use Wilead\IArtistBundle\Form\UserResumeType;
use Wilead\IArtistBundle\Entity\UserResume;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Wilead\ApiBundle\Form\UserLoginType;

/**
 * Description of UserController
 *
 * @author jack
 */
class UserController extends ApiController
{

    /**
     * @ApiDoc(
     *      description="101用户位置设置"
     * )
     * @RequestParam(name="longitude", requirements="float", description="经度", nullable=false)
     * @RequestParam(name="latitude", requirements="float", description="纬度", nullable=false)
     */
    public function gisAction($id)
    {
        /** @var \Wilead\IArtistBundle\Entity\User $user */
        $user = $this->getDoctrine()->getManager()->getRepository('WileadIArtistBundle:User')->find($id);
        $request = $this->getRequest()->request;
        $em = $this->getEntityManager();

        if ($user) {
            $user->setPointx($request->get('longitude'));
            $user->setPointy($request->get('latitude'));
            $em->persist($user);
            $em->flush();

            return $this->getFOSView()->setData('定位成功')->setStatusCode(200);
        }
    }

    /**
     * @ApiDoc(
     *      description="用户找回密码"
     * )
     * @RequestParam(name="mobile", requirements="string", description="手机号码")
     */
    public function resetPasswordAction()
    {
        $request = $this->getRequest()->request;

        $mobile = $request->get('mobile');
        $user = $this->getRepository('WileadIArtistBundle:User')->findOneBy(array('mobile' => $mobile));

        $view = $this->getFOSView();
        if ($user) {
            $newPassword = rand(100000, 999999);
            $user->setPassword(md5($newPassword));
            $em = $this->getEntityManager();
            $em->persist($user);
            $em->flush();
            $sms = $this->get('sms.service_ym');
            $sms->sendSMS($mobile, '您的“i艺人”新密码为' . $newPassword . '，请使用新密码登录，不要把密码泄露给他人');
            return $view->setData('新密码已通过短信方式发送到手机，请查收')->setStatusCode(200);
        } else {
            return $view->setData('用户不存在')->setStatusCode(404);
        }
    }

    /**
     * @ApiDoc(
     *      description="获取目标用户对当前用户授权接口"
     * )
     * @RequestParam(name="uid", requirements="integer", description="当前用户ID")
     * @RequestParam(name="tid", requirements="integer", description="目标用户ID")
     */
    public function authorizeAction()
    {
        $repository = $this->getRepository('WileadIArtistBundle:User');
        $request = $this->getRequest()->request;

        /* @var $user User */
        $user = $repository->find($request->get('uid'));
        /* @var $targetUser User */
        $targetUser = $repository->find($request->get('tid'));

        $isFriends = $repository->isFriends($user->getId(), $targetUser->getId());
        $isOrganization = $user->getAccountType() == User::ACCOUNT_TYPE_ORGANIZATION ? TRUE : FALSE;

        $authorize = array('albumsView' => FALSE, 'videoView' => FALSE, 'resumeView' => FALSE);

        // 相册检测
        if ($targetUser->getAlbumsViewAll()) {
            if ($targetUser->getAlbumsViewFriend() && $targetUser->getAlbumsViewOrganization()) {
                $authorize['albumsView'] = TRUE;
            }
        } else {
            if ($targetUser->getAlbumsViewFriend()) {
                if ($isFriends) {
                    $authorize['albumsView'] = TRUE;
                }
            }
            if ($targetUser->getAlbumsViewOrganization()) {
                if ($isOrganization) {
                    $authorize['albumsView'] = TRUE;
                }
            }
        }

        // 视频检测
        if ($targetUser->getVideoViewAll()) {
            if ($targetUser->getVideoViewFriend() && $targetUser->getVideoViewOrganization()) {
                $authorize['videoView'] = TRUE;
            }
        } else {
            if ($targetUser->getVideoViewFriend()) {
                if ($isFriends) {
                    $authorize['videoView'] = TRUE;
                }
            }
            if ($targetUser->getVideoViewOrganization()) {
                if ($isOrganization) {
                    $authorize['videoView'] = TRUE;
                }
            }
        }

        // 简历检测
        if ($targetUser->getResumeViewAll()) {
            if ($targetUser->getResumeViewFriend() && $targetUser->getResumeViewOrganization()) {
                $authorize['resumeView'] = TRUE;
            }
        } else {
            if ($targetUser->getResumeViewFriend()) {
                if ($isFriends) {
                    $authorize['resumeView'] = TRUE;
                }
            }
            if ($targetUser->getResumeViewOrganization()) {
                if ($isOrganization) {
                    $authorize['resumeView'] = TRUE;
                }
            }
        }

        return $this->getFOSView()->setStatusCode(200)->setData($authorize);
    }

    /**
     * @ApiDoc(
     *      description="用户主要技能设置"
     * )
     * @RequestParam(name="skill", requirements="string", description="主要技能")
     */
    public function setMasterSkillAction($id)
    {
        /* @var $user User */
        $user = $this->getRepository('WileadIArtistBundle:User')->find($id);

        $view = $this->getFOSView();

        if (!$user)
            return $view->setData('无此用户')->setStatusCode(404);

        $em = $this->getEntityManager();
        $user->setMasterSkill($this->getRequest()->request->get('skill'));
        $em->persist($user);
        $em->flush();

        return RouteRedirectView::create('wilead_api_user_get', array('id' => $user->getId()), 200);
    }

    /**
     * @ApiDoc(
     *      description="102注册验证码获取"
     * )
     * @RequestParam(name="mobile", requirements="integer", description="手机号码", nullable=false)
     */
    public function verifycodeAction()
    {
        $mobile = $this->getRequest()->request->get('mobile');
        if ($mobile === NULL) {
            return $this->getFOSView()->setStatusCode(403)->setData('手机号码不能为空');
        } else {
            $verifyCode = rand(1000, 9999);
            $sms = $this->get('sms.service_ym');
            $sms->sendSMS($mobile, '您的“i艺人”验证码为' . $verifyCode . '，请尽快注册，不要把验证码泄露给他人');
            return $this->getFOSView()->setStatusCode(200)->setData(array(
                'mobile' => $mobile,
                'verifyCode' => $verifyCode
            ));
        }
    }

    /**
     * @ApiDoc(
     *      description="获取用户资料"
     * )
     */
    public function getAction($id)
    {
        $qb = $this->getRepository('WileadIArtistBundle:User')->createQueryBuilder('q');
        $user = $qb
            ->select('q, r, i, s, a, v')
            ->leftJoin('q.UserResume', 'r')
            ->leftJoin('q.UserIntroduction', 'i')
            ->leftJoin('q.UserSkills', 's')
            ->leftJoin('q.UserAlbums', 'a')
            ->leftJoin('q.UserVideos', 'v')
            ->where('q.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->getArrayResult();

        $view = FOSView::create();
        if ($user) {
            $view->setStatusCode(200)->setData($user);
        }

        return $view;
    }

    /**
     * @ApiDoc(
     *      description="我申请的职位"
     * )
     */
    public function getJobsAction($id)
    {
        $qb = $this->getRepository('WileadIArtistBundle:JobResume')->createQueryBuilder('q');

        $qb
            ->select('q, j')
            ->leftJoin('q.userResume', 'r')
            ->leftJoin('q.Job', 'j')
            ->where('r.User = :id')->setParameter('id', $id)
            ->orderBy('q.created', 'DESC');

        return $this->getFOSView()->setStatusCode(200)->setData($qb->getQuery()->getArrayResult());
    }

    /**
     * @ApiDoc(
     *      description="获取用户列表"
     * )
     */
    public function getUsersAction()
    {
        /* @var $queryBuilder \Doctrine\ORM\QueryBuilder */
        $queryBuilder = $this->getDoctrine()->getManager()->getRepository('WileadIArtistBundle:User')->createQueryBuilder('q');
        $users = $queryBuilder
            ->select('q, r')
            ->leftJoin('q.UserResume', 'r')
            ->orderBy('q.firstWord', 'ASC')
            ->getQuery()
            ->getArrayResult();

        $view = FOSView::create();
        if ($users) {
            $view->setStatusCode(200)->setData($users);
        } else {
            $view->setStatusCode(404);
        }
        return $view;
    }

    /**
     * @ApiDoc(
     *      description="用户添加好友"
     * )
     * @RequestParam(name="uid", requirements="\d+", description="用户ID", nullable=false)
     * @RequestParam(name="fid", requirements="\d+", description="好友ID", nullable=false)
     */
    public function addFriendAction()
    {
        return $this->processFriends('add');
    }

    /**
     * @ApiDoc(
     *      description="用户添加好友（通过艺人号）"
     * )
     * @RequestParam(name="uid", requirements="\d+", description="用户ID", nullable=false)
     * @RequestParam(name="systemNum", requirements="\d+", description="好友艺人号", nullable=false)
     */
    public function addFriendWithNumAction()
    {
        $uid = $this->getRequest()->request->get('uid');
        $systemNum = $this->getRequest()->request->get('systemNum');

        $user = $this->getRepository('WileadIArtistBundle:User')->getUserWithNum($systemNum);

        if (!$user)
            return $this->getFOSView()->setStatusCode(404)->setData('艺人不存在或不允许通过艺人号添加');

        return $this->processFriends('add', $uid, $user->getId(), true);
    }

    /**
     * @ApiDoc(
     *      description="用户删除好友"
     * )
     * @RequestParam(name="uid", requirements="\d+", description="用户ID", nullable=false)
     * @RequestParam(name="fid", requirements="\d+", description="好友ID", nullable=false)
     */
    public function deleteFriendAction()
    {
        return $this->processFriends('delete');
    }

    /**
     * @ApiDoc(
     *      description="用户搜索接口",
     *      filters={
     *          {"name"="systemNum", "dataType"="integer", "description"="艺人号"},
     *          {"name"="keyword", "dataType"="string", "description"="关键字"},
     *          {"name"="liveplace", "dataType"="string", "description"="现居城市"},
     *          {"name"="sex", "dataType"="string", "pattern"="m|f", "description"="性别"},
     *          {"name"="age", "dataType"="integer", "pattern"="15,21","description"="年龄"},
     *          {"name"="points", "dataType"="string", "pattern"="104.092759,30.561242","description"="坐标"},
     *          {"name"="skill", "dataType"="string", "description"="技能"}
     *      }
     * )
     */
    public function searchAction()
    {
        $qb = $this->getEntityManager()->getRepository('WileadIArtistBundle:User')->createQueryBuilder('q');

        $year = intval(date('Y'));
        $emConfig = $this->getEntityManager()->getConfiguration();
        $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');

        $qb
            ->select('q, r, s')
            ->leftJoin('q.UserResume', 'r')
            ->leftJoin('q.UserSkills', 's')
            ->andWhere('q.searchAble = :searchAble')->setParameter('searchAble', true);

        $request = $this->getRequest()->request;

        if ($request->has('systemNum')) {
            $qb->andWhere('q.systemNum = :systemNum')->setParameter('systemNum', $request->get('systemNum'));
        }

        if ($request->has('skill')) {
            $qb->andWhere('s.skill LIKE :skill')->setParameter('skill', $request->get('skill'));
        }

        if ($request->has('keyword')) {
            $qb->where('r.name LIKE :keyword')->setParameter('keyword', $request->get('keyword'));
        }

        if ($request->has('sex')) {
            $qb->andWhere('q.sex = :sex')->setParameter('sex', $request->get('sex'));
        }

        if ($request->has('liveplace')) {
            $qb->andWhere('r.liveplace = :liveplace')->setParameter('liveplace', $request->get('liveplace'));
        }

        if ($request->has('points')) {
            $points = explode(',', $request->get('points'));
            $qb->andWhere('(q.pointx LIKE :pointx) AND (q.pointy LIKE :pointy)')
                ->setParameter('pointx', substr($points[0], 0, 5) . '%')
                ->setParameter('pointy', substr($points[1], 0, 4) . '%');
        }

        if ($request->has('age')) {
            $age = explode(',', $request->get('age'));
            $qb->andWhere($year . ' - YEAR(r.brithday) >= :year_from')->setParameter('year_from', $age[0]);
            $qb->andWhere($year . ' - YEAR(r.brithday) <= :year_to')->setParameter('year_to', $age[1]);
        }

        $qb->orderBy('q.id', 'DESC');

        $result = $qb->getQuery()->getArrayResult();

        return $this->getFOSView()->setData($result)->setStatusCode(200);
    }

    /**
     * @ApiDoc(
     *      description="获取用户好友列表"
     * )
     */
    public function getFriendsAction($id)
    {
        /* @var $qb \Doctrine\ORM\QueryBuilder */
        $qb = $this->getDoctrine()->getManager()->getRepository('WileadIArtistBundle:User')->createQueryBuilder('q');

        $blackLists = $this->getDoctrine()->getManager()->getRepository('WileadIArtistBundle:User')->getUserBlackList($id, TRUE);

        $qb
            ->select('q, f, r')
            ->leftJoin('q.Friends', 'f')
            ->leftJoin('f.UserResume', 'r')
            ->where('q.id = :id')
            ->setParameter('id', $id);

        if (count($blackLists) > 0) {
            $qb
                ->andWhere('r.User NOT IN (:ids)')
                ->setParameter('ids', $blackLists);
        }

        $friends = $qb
            ->getQuery()
            ->getArrayResult();

        $view = FOSView::create();

        if ($friends) {
            /* @var $user \User */
            $view->setStatusCode(200)->setData($friends);
        } else {
            $view->setStatusCode(404);
        }

        return $view;
    }

    /**
     * @ApiDoc(
     *      description="用户登录接口"
     * )
     * @RequestParam(name="mobile", requirements="\d+", description="手机号码", nullable=false)
     * @RequestParam(name="password", requirements="\d{11}", description="密码", nullable=false)
     */
    public function loginAction()
    {
        $request = $this->getRequest();
        $view = FOSView::create();
        if ($request->request->has('mobile') && $request->request->has('password')) {
            $mobile = $request->request->get('mobile');
            $password = md5($request->request->get('password'));

//            $user = $this->getRepository('WileadIArtistBundle:User')->findBy(array(
//                'mobile' => $mobile,
//                'password' => $password
//            ));
            $qb = $this->getRepository('WileadIArtistBundle:User')->createQueryBuilder('q');
//
            $user = $qb
                ->select('q, r, a, v, s, i')
                ->leftJoin('q.UserResume', 'r')
                ->leftJoin('q.UserAlbums', 'a')
                ->leftJoin('q.UserVideos', 'v')
                ->leftJoin('q.UserSkills', 's')
                ->leftJoin('q.UserIntroduction', 'i')
                ->where('q.mobile = :mobile')->setParameter('mobile', $mobile)
                ->andWhere('q.password = :password')->setParameter('password', $password)
                ->getQuery()
                ->getOneOrNullResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);

            if ($user) {
                $view->setStatusCode(200);
                $view->setData($user);
            } else {
                $view->setStatusCode(404);
            }
        } else {
            $view->setStatusCode(400);
        }
        return $view;
    }

    /**
     * @ApiDoc(
     *      description="用户注册"
     * )
     * @RequestParam(name="mobile", requirements="\d+", description="手机号码", nullable=false)
     * @RequestParam(name="password", requirements="\d{11}", description="密码", nullable=false)
     */
    public function newAction()
    {
        return $this->processUserForm(new User);
    }

    /**
     * @ApiDoc(
     *      description="获取好友请求列表"
     * )
     */
    public function getRequestAction($id)
    {
        $queryBuilder = $this->getRepository('WileadIArtistBundle:FriendRequest')->createQueryBuilder('q');

        $list = $queryBuilder
            ->select('q, u')
            ->leftJoin('q.Uid', 'u')
            ->where('q.Tid = :tid')
            ->setParameter('tid', $id)
            ->getQuery()
            ->getArrayResult();

        $view = $this->getFOSView();
        return $view->setStatusCode(200)->setData($list);
    }

    /**
     * @ApiDoc(
     *      description="好友请求处理"
     * )
     * @RequestParam(name="action", requirements="string", description="yes同意no拒绝,默认yes")
     */
    public function requestHandleAction($id)
    {
        /** @var \Wilead\IArtistBundle\Entity\FriendRequest $result */
        $result = $this->getRepository('WileadIArtistBundle:FriendRequest')->find($id);
        /** @var \Wilead\IArtistBundle\Repository\UserRepository $repo */
        $repo = $this->getRepository('WileadIArtistBundle:User');

        $view = $this->getFOSView();
        if ($result) {
            $action = ($this->getRequest()->request->get('action') == 'yes') ? 'yes' : 'no';
            $uid = $result->getUid()->getId();
            $fid = $result->getTid()->getId();
            $isFriend = $repo->isFriends($uid, $fid);
            if ($action === 'yes' && !$isFriend) {
                $uid = $result->getUid()->getId();
                $fid = $result->getTid()->getId();
                $this->processFriends('add', $uid, $fid, false);
            }
            $this->getRepository('WileadIArtistBundle:FriendRequest')->deleteRequest($result->getId());
            return $view->setData('处理成功')->setStatusCode(200);
        } else {
            return $view->setData('未找到该请求')->setStatusCode(404);
        }
    }

    /**
     * 好友处理
     * @param string $action add添加 delete删除
     */
    protected function processFriends($action, $userId = NULL, $friendId = NULL, $validate = true)
    {
        $uid = is_null($userId) ? $this->getRequest()->request->get('uid') : $userId;
        $fid = is_null($friendId) ? $this->getRequest()->request->get('fid') : $friendId;

        $em = $this->getDoctrine()->getManager();
        /** @var User $user */
        $user = $em->getRepository('WileadIArtistBundle:User')->find($uid);
        $friend = $em->getRepository('WileadIArtistBundle:User')->find($fid);

        $inMyBlackList = $em->getRepository('WileadIArtistBundle:User')->isInBlackList($fid, $uid);
        $inHimBlackList = $em->getRepository('WileadIArtistBundle:User')->isInBlackList($uid, $fid);

        if ($inHimBlackList || $inMyBlackList) {
            if ($inMyBlackList) {
                return $this->getFOSView()->setStatusCode(403)->setData('该用户在您的黑名单中,无法添加为好友');
            }
            if ($inHimBlackList) {
                return $this->getFOSView()->setStatusCode(403)->setData('该用户已把你列入黑名单,无法添加为好友');
            }
        }

        $view = FOSView::create();

        // 判断是否需要验证
        if ($friend->getFriendVerification() && $validate && $action == 'add') {
            /** @var \Wilead\IArtistBundle\Repository\FriendRequestRepository $friendRequest */
            $friendRequest = $em->getRepository('WileadIArtistBundle:FriendRequest');
            // 需要验证
            // 判断是否已经在验证列表
            if (!$friendRequest->hasRequest($user, $friend)) {
                $friendRequest->addRequest($user, $friend);
                return $view->setStatusCode(202)->setData('好友请求已发送，请等待验证');
            } else {
                return $view->setStatusCode(202)->setData('您已发起过请求，请等待验证');
            }
        }

        if ($user && $friend) {
            /* @var $user \User */
            switch ($action) {
                case 'add':
                    $user->addFriend($friend);
                    $friend->addFriend($user);
                    break;
                case 'delete':
                    $user->removeFriend($friend);
                    $friend->removeFriend($user);
                    break;
            }
            $em->persist($user);
            $em->persist($friend);
            $em->flush();

            return RouteRedirectView::create('wilead_api_user_get_friends', array('id' => $user->getId()), 204);
        } else {
            return $view->setStatusCode(404);
        }

        return $view->setStatusCode(400);
    }

    /**
     * @ApiDoc(
     *      description="编辑用户简历"
     * )
     * @RequestParam(name="name", requirements="string", description="姓名")
     * @RequestParam(name="brithday", requirements="string(Y-m-d)", description="出生日期", nullable=true)
     * @RequestParam(name="birthplace", requirements="string", description="籍贯", nullable=true)
     * @RequestParam(name="liveplace", requirements="string", description="长期居住地", nullable=true)
     * @RequestParam(name="ethnic", requirements="string", description="民族", nullable=true)
     * @RequestParam(name="height", requirements="string", description="身高", nullable=true)
     * @RequestParam(name="bodyWeight", requirements="string", description="体重", nullable=true)
     * @RequestParam(name="school", requirements="string", description="专业培训学校", nullable=true)
     * @RequestParam(name="specialty", requirements="string", description="专业", nullable=true)
     * @RequestParam(name="specialty2", requirements="string", description="专业2", nullable=true)
     * @RequestParam(name="workExp", requirements="string", description="工作经验", nullable=true)
     * @RequestParam(name="workExp2", requirements="string", description="工作经验2", nullable=true)
     * @RequestParam(name="workExp3", requirements="string", description="工作经验3", nullable=true)
     * @RequestParam(name="workExp4", requirements="string", description="工作经验4", nullable=true)
     * @RequestParam(name="workExp5", requirements="string", description="工作经验5", nullable=true)
     * @RequestParam(name="intention", requirements="string", description="求职意向", nullable=true)
     * @RequestParam(name="graduationAt", requirements="string", description="毕业院校", nullable=true)
     * @RequestParam(name="skillDescription", requirements="string", description="专业技能描述", nullable=true)
     * @RequestParam(name="valuate", requirements="string", description="自我评价", nullable=true)
     * @RequestParam(name="diploma", requirements="string", description="学历", nullable=true)
     */
    public function resumeEditAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        $userResume = $em->getRepository('WileadIArtistBundle:UserResume')->find($id);

        if (!$userResume) {
            $userResume = new UserResume;
            $userResume->setUser($em->getReference('Wilead\IArtistBundle\Entity\User', $id));
        }

        return $this->processUserResumeType($userResume);
    }

    /**
     * @ApiDoc(
     *      description="用户基本信息修改"
     * )
     * @RequestParam(name="name", requirements="string", description="姓名")
     * @RequestParam(name="nickname", requirements="string", description="昵称")
     * @RequestParam(name="password", requirements="string", description="密码")
     * @RequestParam(name="avatar", requirements="string", description="头像地址")
     * @RequestParam(name="sex", requirements="string", description="性别（m男f女）")
     * @RequestParam(name="signature", requirements="string", description="个人签名")
     * @RequestParam(name="accountType", requirements="string", description="账号类型（artist艺人organization机构）")
     */
    public function baseInfoEditAction($id)
    {
        $request = $this->getRequest()->request;
        /* @var $user \User */
        $user = $this->getEntityManager()->getRepository('WileadIArtistBundle:User')->find($id);

        if (!$user)
            throw $this->createNotFoundException();

        $resume = $user->getUserResume();

        if (!$resume) {
            $resume = new UserResume;
            $resume->setUser($user);
        }

        if ($request->has('name')) {
            $resume->setName($request->get('name'));
        }

        if ($request->has('nickname')) {
            $user->setNickname($request->get('nickname'));
        }

        if ($request->has('password')) {
            $user->setPassword(md5($request->get('password')));
        }

        if ($request->has('avatar')) {
            $user->setAvatar($request->get('avatar'));
        }

        if ($request->has('sex')) {
            $user->setSex($request->get('sex'));
        }

        if ($request->has('signature')) {
            $user->setSignature($request->get('signature'));
        }

        if ($request->has('accountType')) {
            $user->setAccountType($request->get('accountType'));
        }

        $em = $this->getEntityManager();
        $em->persist($resume);
        $em->persist($user);
        $em->flush();

        return RouteRedirectView::create('wilead_api_user_get', array('id' => $user->getId()), 200);
    }

    /**
     * @ApiDoc(
     *      description="获取系统时间"
     * )
     */
    public function getDateTimeAction()
    {
        return $this->getFOSView()->setStatusCode(200)->setData(new \DateTime());
    }

    /**
     * @ApiDoc(
     *      description="获取用户简历"
     * )
     */
    public function getUserResumeAction($id)
    {
        $qb = $this->getRepository('WileadIArtistBundle:UserResume')->createQueryBuilder('q');

        $userResume = $qb
            ->select('q, u')
            ->leftJoin('q.User', 'u')
            ->where('q.User = :id')->setParameter('id', $id)
            ->getQuery()
            ->getArrayResult();

        $view = FOSView::create();
        if ($userResume) {
            $view->setStatusCode(200)->setData($userResume);
        }

        return $view;
    }

    /**
     * @ApiDoc(
     *      description="用户充值接口"
     * )
     * @RequestParam(name="totalMonth", requirements="integer", description="充值月份")
     */
    public function rechargeAction($id)
    {
        /* @var $user \User */
        $user = $this->getRepository('WileadIArtistBundle:User')->find($id);

        $view = $this->getFOSView();
        if (!$user) {
            return $view->setStatusCode(404)->setData('无法找到该用户');
        }

        $request = $this->getRequest()->request;

        /* @var $expired \DateTime */
        $expiredAt = $user->getMemberExpiredAt();
        if ($expiredAt === NULL) {
            $expired = new \DateTime;
        } else {
            $expired = new \DateTime($expiredAt->format('Y-m-d H:i:s'));
        }
        $expired->add(new \DateInterval('P' . $request->get('totalMonth') . 'M'));
        $user->setMemberExpiredAt($expired);

        $em = $this->getEntityManager();
        $em->persist($user);
        $em->flush();

        return RouteRedirectView::create('wilead_api_user_get', array('id' => $user->getId()), 200);
    }

    /**
     * @ApiDoc(
     *      description="用户权限设置"
     * )
     * @RequestParam(name="friendVerification", requirements="boolean", description="加好友需要验证")
     * @RequestParam(name="searchAble", requirements="boolean", description="是否可被搜索")
     * @RequestParam(name="albumsViewAll", requirements="boolean", description="相册所有人可见")
     * @RequestParam(name="albumsViewFriend", requirements="boolean", description="相册好友可见")
     * @RequestParam(name="albumsViewOrganization", requirements="boolean", description="相册机构可见")
     * @RequestParam(name="videoViewAll", requirements="boolean", description="视频所有人可见")
     * @RequestParam(name="videoViewFriend", requirements="boolean", description="视频好友可见")
     * @RequestParam(name="videoViewOrganization", requirements="boolean", description="视频机构可见")
     * @RequestParam(name="resumeViewAll", requirements="boolean", description="简历所有人可见")
     * @RequestParam(name="resumeViewFriend", requirements="boolean", description="简历好友可见")
     * @RequestParam(name="resumeViewOrganization", requirements="boolean", description="简历机构可见")
     */
    public function privacyAction($id)
    {
        $user = $this->getDoctrine()->getManager()->getRepository('WileadIArtistBundle:User')->find($id);

        $view = FOSView::create();
        if (!$user) {
            $view->setStatusCode(404);
        }

        $form = $this->createForm(new \Wilead\ApiBundle\Form\UserPrivacyType(), $user);
        $form->bind($this->getRequest());
        $validator = $this->get('validator');
        $errors = $validator->validate($user);
        if (count($errors) == 0) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            $view = RouteRedirectView::create('wilead_api_user_get', array('id' => $user->getId()), 200);
        } else {
            $view = $this->getErrorsView($errors);
        }

        return $view;
    }

    /**
     * @param User $user
     * @return FOSView
     */
    protected function processUserForm(User $user)
    {
        $statusCode = $user->getId() ? 201 : 204;

        $form = $this->createForm(new UserType, $user);
        $form->bind($this->getRequest(json_decode($this->getRequest()->getContent()), TRUE));

        $validator = $this->get('validator');
        $errors = $validator->validate($user);
        if (count($errors) == 0) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            $view = RouteRedirectView::create('wilead_api_user_get', array('id' => $user->getId()), $statusCode);
        } else {
            $view = $this->getErrorsView($errors);
        }

        return $view;
    }

    /**
     *  个人简历表单处理
     */
    protected function processUserResumeType(UserResume $userResume)
    {
        $form = $this->createForm(new UserResumeType, $userResume);
        $form->bind($this->getRequest());

        $validator = $this->get('validator');
        $errors = $validator->validate($userResume);
        if (count($errors) == 0) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($userResume);
            $em->flush();

            $view = RouteRedirectView::create('wilead_api_userresume_get', array('id' => $userResume->getUser()->getId()), 200);
        } else {
            $view = $this->getErrorsView($errors);
        }

        return $view;
    }

}

?>
